<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Repositories\Contracts\RoleRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class RoleController extends Controller
{
  /**
   * @var RoleRepositoryInterface $roleRepository
   */
  private $roleRepository;

  public function __construct(RoleRepositoryInterface $roleRepository)
  {
    $this->roleRepository = $roleRepository;
  }

  /**
   * 管理员，对用户进行修改，新增操作
   *
   * @param Request $request
   *
   * @return \Illuminate\Http\JsonResponse
   */
  public function save(Request $request)
  {
    $id = $request->post('id') ?: 0;
    $data = $request->only('name', 'guard_name');
    $this->validation($request, $id);
    $data = $this->roleRepository->save($data, $id);
    return $this->resultData($data);
  }


  public function lists()
  {
    $result = $this->roleRepository->paginate();
    return $this->result(true, $result);
  }

  public function info($id)
  {
    return $this->resultData($this->roleRepository->get_role_and_permissions($id));
  }

  public function all()
  {
    $result = $this->roleRepository->all(['id', 'name']);
    return $this->result(true, $result);
  }

  public function remove($id = 0)
  {

    return $this->result($this->roleRepository->delete($id));
  }

  public function save_permission(Request $request)
  {
    $roleId = intval($request->input('roleId'));
    $permissions = $request->input("permissions");
    return $this->result($this->roleRepository->save_permission($roleId, $permissions));
  }

  protected function validation($request, $id)
  {

    $role = [
      'name' => ['required', 'string', 'max:255'],
      'guard_name' => ['required', 'string'],
    ];
    if ($id < 1) {
      // 新用户做唯一性检测
      $role['name'][] = "unique:roles,name";
    } else {
      $role['name'][] = Rule::unique('roles')->ignore($id);
    }

    $this->validateWith($role, $request);
  }
}
